<template>
  <div class="filter-container">
    <el-button class="filter-item" type="primary" icon="el-icon-upload2" @click="exportMany">批量导入</el-button>
    <el-button class="filter-item" type="primary" icon="el-icon-circle-plus-outline" @click="handleAddWords">新增</el-button>
    <el-button class="filter-item" type="primary" icon="el-icon-delete" @click="deleteWords">删除选中</el-button>
    <el-table :data="list" v-loading="listLoading" element-loading-text="给我一点时间" border fit highlight-current-row
              style="width: 100%" max-height="580" @selection-change="handleSelectionChange" @row-click="handleUpdateWords">
      <el-table-column type="selection" align="center" label="选择" width="65">
      </el-table-column>
      <el-table-column width="220px" align="center" label="分类" v-if="false">
        <template slot-scope="scope">
          <span>{{scope.row.type_id}}</span>
        </template>
      </el-table-column>
      <el-table-column width="220px" align="center" label="话术标题">
        <template slot-scope="scope">
          <span>{{scope.row.t_title}}</span>
        </template>
      </el-table-column>
      <el-table-column min-width="180px" align="center" label="话术内容">
        <template slot-scope="scope">
          <span>{{scope.row.t_content}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="最后修改时间" width="220" class-name="small-padding">
        <template slot-scope="scope">
          <span>{{scope.row.update_time | parseTime('{y}-{m}-{d} {h}:{i}:{s}')}}</span>
        </template>
      </el-table-column>
      <el-table-column width="220px" align="center" label="最后修改人">
        <template slot-scope="scope">
          <span>{{scope.row.update_uid_text}}</span>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog width="500px" :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
        <el-form :rules="rules" status-icon ref="dataForm" :model="temp" label-position="left" label-width="70px" >
          <el-form-item label="分类" prop="type_id">
            <el-select v-model="temp.type_id" placeholder="请选择">
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="修改时间" prop="updateTime" v-show="dialogUpdateShow">
            <span style="margin-left:16px;">{{temp.update_time | parseTime('{y}-{m}-{d} {h}:{i}:{s}')}}</span>
          </el-form-item>
          <el-form-item label="修改人" prop="updatePerson" v-show="dialogUpdateShow">
            <span v-html="temp.update_uid_text" style="margin-left:16px;"></span>
          </el-form-item>
          <el-form-item label="标题" prop="t_title">
              <el-input v-model="temp.t_title" placeholder="请输入话术标题"></el-input>
          </el-form-item>
          <el-form-item label="内容" prop="t_content">
            <el-input type="textarea" v-model="temp.t_content" placeholder="请输入话术内容"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button v-show="dialogUpdateShow" type="primary" @click="updateWords">修改</el-button>
          <el-button v-show="!dialogUpdateShow" type="primary" @click="addWords">新增</el-button>
        </div>
    </el-dialog>
    <el-dialog width="30%" :visible.sync="dialogUpload">
      <el-upload
        class="upload-demo"
        ref="upload"
        action="http://jbapi.dsjb.com/talk/uploadtalk"
        :limit="1"
        :data="dataParams"
        :on-preview="handlePreview"
        :on-remove="handleRemove"
        :on-success="handleSuccess"
        :on-error="handleError"
        :on-exceed="handleExceed"
        :file-list="fileList"
        :before-upload="beforeAvatarUpload"
        :auto-upload="false">
        <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
        <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button>
        <div slot="tip" class="el-upload__tip">请按照话术模板格式上传excel文件，且大小不超过2M。</div>
      </el-upload>
    </el-dialog>
    <el-dialog
      title="提示"
      :visible.sync="dialogError"
      width="30%">
      <div style="overflow: auto;max-height:300px">
        <span v-html="showErrorText"></span>
      </div>
      <span slot="footer" class="dialog-footer"></span>
    </el-dialog>

  </div>
</template>
<style>
  div.dialog-footer{
    text-align: center;
    padding-bottom:10px;
  }
  div.dialog-footer .el-button{
    width:100px;
  }
</style>
<script>
  import { subComma } from '@/utils'
  import store from '@/store'
  export default {
    props: {
      list: Array,
      options: Array,
      listLoading: Boolean
    },
    data() {
      return {
        check_str: '',
        temp: {
          id: undefined,
          type_id: undefined,
          update_time: '',
          update_uid_text: '',
          t_title: '',
          t_content: ''
        },
        dialogFormVisible: false,
        dialogStatus: '',
        dialogUpdateShow: false,
        dialogUpload: false,
        dialogError: false,
        loading: false,
        isExcel: false,
        isExcel2: false,
        isLt2M: false,
        isUploadFlag: false,
        showErrorText: '',
        fileList: [],
        dataParams: { token: store.getters.token },
        oldWordsValue: {},
        textMap: {
          create: '新增话术信息',
          update: '修改话术信息'
        },
        rules: {
          type_id: [{ required: true, message: '请选择分类', trigger: 'change' }],
          t_title: [{ required: true, message: '话术标题不能为空', trigger: 'blur' }, { max: 100, message: '话术标题长度不能大于100个字符', trigger: 'blur' }],
          t_content: [{ required: true, message: '话术内容不能为空', trigger: 'blur' }, { max: 500, message: '话术内容长度不能大于500个字符', trigger: 'blur' }]
        }
      }
    },
    created() {
    },
    methods: {
      handleSelectionChange(val) {
        var str = ''
        for (const v of val) {
          str += v.id + ','
        }
        this.check_str = subComma(str)
      },
      exportMany() {
        // 批量导入
        this.fileList = []
        this.dialogUpload = true
      },
      openFullScreen2() {
        this.loading = this.$loading({
          lock: true,
          text: '正在努力上传中...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.3)'
        })
      },
      submitUpload() {
        this.$refs.upload.submit()
        if (!(this.isExcel || this.isExcel2 && this.isLt2M)) {
          if (!this.isUploadFlag) {
            this.$message({
              type: 'error',
              message: '请选取要上传的文件'
            })
          } else {
            this.isUploadFlag = false
          }
        }
        if (this.isExcel || this.isExcel2 && this.isLt2M) {
          this.openFullScreen2()
        }
      },
      handleSuccess(response, file, fileList) {
        this.loading.close()
        if (response.code === '200') {
          this.dialogUpload = false
          this.$message({
            type: 'success',
            message: '导入成功'
          })
          this.$emit('get-list')
        } else {
          this.dialogUpload = false
          this.dialogError = true
          var errorStr = response.msg + '</br>'
          if (response.data) {
            for (const item of response.data) {
              var itemStr = JSON.stringify(item)
              errorStr = errorStr + itemStr.substring(1, itemStr.length - 1) + '</br>'
            }
          }
          this.showErrorText = errorStr
        }
        this.isExcel = false
        this.isExcel2 = false
        this.isLt2M = false
      },
      handleExceed(files, fileList) {
        this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
      },
      handleError(err, file, fileList) {
        console.log(err)
        this.loading.close()
      },
      handleRemove(file, fileList) {
        console.log(file, fileList)
      },
      handlePreview(file) {
        console.log(file)
      },
      beforeAvatarUpload(file) {
        this.isExcel = file.name.split('.')[1] === 'xls'
        this.isExcel2 = file.name.split('.')[1] === 'xlsx'
        this.isLt2M = file.size / 1024 / 1024 < 2
        if (!this.isExcel && !this.isExcel2) {
          this.$message.error('上传文件只能是excel文件!')
          this.isUploadFlag = true
        }
        if (!this.isLt2M) {
          this.$message.error('上传文件不能超过 2MB!')
          this.isUploadFlag = true
        }
        return this.isExcel || this.isExcel2 && this.isLt2M
      },
      handleAddWords() {
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.dialogUpdateShow = false
        this.temp = {
          id: undefined,
          type_id: undefined,
          t_title: '',
          t_content: ''
        }
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      addWords() {
        // 新增
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            const addData = Object.assign({}, this.temp)
            const flag = this.$emit('add-words', addData)
            if (flag) {
              this.dialogFormVisible = false
              this.$message({
                type: 'success',
                message: '新增成功'
              })
            }
          }
        })
      },
      deleteWords() {
        // 删除
        this.$emit('get-words', this.check_str)
      },
      handleUpdateWords(row, event, column) {
        // 修改
        if (column.label !== '选择') {
          this.temp = Object.assign({}, row)
          this.dialogStatus = 'update'
          this.dialogFormVisible = true
          this.dialogUpdateShow = true
          this.oldWordsValue = Object.assign({}, { type_id: row.type_id }, { t_title: row.t_title }, { t_content: row.t_content })
          this.$nextTick(() => {
            this.$refs['dataForm'].clearValidate()
          })
        }
      },
      updateWords() {
        // 修改数据
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            if (this.oldWordsValue.type_id === this.temp.type_id && this.oldWordsValue.t_title === this.temp.t_title && this.oldWordsValue.t_content === this.temp.t_content) {
              this.$message({
                type: 'warning',
                message: '没有任何修改'
              })
            } else {
              const tempData = Object.assign({}, this.temp)
              const flag = this.$emit('update-words', tempData)
              if (flag) {
                this.dialogFormVisible = false
                this.$message({
                  type: 'success',
                  message: '修改成功'
                })
              }
            }
          }
        })
      }
    }
  }
</script>
